/*
 * Client.c
 * 
 */

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main()
{
	int sock, bytes_received, invalid, i; 
	char send_data[1024],recv_data[1024];
	struct hostent *host;
	struct sockaddr_in server_addr;  

	host = gethostbyname("127.0.0.1");

	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("Socket");
		exit(1);
	}

	server_addr.sin_family = AF_INET;     
	server_addr.sin_port = htons(5000);   
	server_addr.sin_addr = *((struct in_addr *)host->h_addr);
	bzero(&(server_addr.sin_zero),8); 

	if (connect(sock, (struct sockaddr *)&server_addr,
		sizeof(struct sockaddr)) == -1) 
	{
		perror("Connect");
		exit(1);
	}
	else
	{
		printf("Connected with server 127.0.0.1:5000\n");
	}

	while(1)
	{
		// examine the input
		do{
			invalid = 0;
			printf("Please input a number(q or Q to quit): ");
			//gets(send_data);
			scanf("%s", send_data);
			// quit the program
			if (strcmp(send_data , "q") == 0 || strcmp(send_data , "Q") == 0)
			{
				close(sock);
				exit(0);
			}
			// make sure the input is an integer
			for(i = 0; i < strlen(send_data); i++) {
				if(send_data[i] < '0' || send_data[i] > '9'){
					invalid = 1;
					break;
				}
			}
		}while(invalid);
		
		// send the integer to the server
		send(sock,send_data,strlen(send_data), 0); 
		
		// receive the feedback from the server
		if((bytes_received = recv(sock, recv_data, 1024, 0)) <= 0)
		{
			printf("Server closed\n");
			close(sock);
			exit(1);
		}
		recv_data[bytes_received] = '\0';
		printf("Recieved data = %s\n" , recv_data);
	   
		// process the string
		printf("Do you want to send the corect response? (Y for yes, N for No): ");
		//gets(send_data);
		scanf("%s", send_data);
		if(strcmp(send_data , "Y") == 0)
		{
			// send the correct string
			i = 0;
			while(recv_data[i] != ' ') i++;
			int string_begin = ++i;
			for(; i < strlen(recv_data); i++)
			{
				if(recv_data[i] >= 'a' && recv_data[i] <= 'z') send_data[i - string_begin] = recv_data[i] - 32;
				else if(recv_data[i] >= 'A' && recv_data[i] <= 'Z') send_data[i - string_begin] = recv_data[i] + 32;
				else send_data[i - string_begin] = recv_data[i];
			}
			send_data[i - string_begin] = '\0';
		}
		else
		{
			// send a wrong string
			i = 0;
			while(recv_data[i] != ' ') i++;
			int string_begin = ++i;
			for(; i < strlen(recv_data); i++)
			{
				send_data[i - string_begin] = 'x';
			}
			send_data[i - string_begin] = '\0';
		}
		send(sock, send_data, strlen(send_data), 0);
		printf("Send: %s \n", send_data);

		// receive the verification of the string
		if((bytes_received = recv(sock, recv_data, 1024, 0)) <= 0)
		{
			printf("Server closed\n");
			close(sock);
			exit(1);
		}
		recv_data[bytes_received] = '\0';
		printf("Received: %s \n", recv_data);
	}   
	return 0;
}
